<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="mainor_form">
        <div class="mainor_te">
          <el-button @click="editAction()" class="marginLeft10" type="primary">新增</el-button>
          <!-- <el-button @click="exportbuVisible = true">导出</el-button> -->
        </div>
        <el-form :inline="true" :model="form" class="demo-form-inline" ref="userListFrom" label-width="80px">
          <el-form-item label="学校名称" prop="school_id">
            <el-select v-model="form.school_id" filterable placeholder="请选择学校名称">
              <el-option v-for="item in schoolList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="广告状态" prop="status">
            <el-select v-model="form.status" clearable placeholder="请选择广告状态" @change="selectAction($event, 'model')">
              <el-option v-for="item in userType" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="客户类型" prop="model">
            
          </el-form-item> -->

          <!-- <div class="more el-form-item" @click="more">
            <span>更多</span>
            <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
          </div> -->

          <!-- <div class="clearfix"></div> -->
          <el-form-item>
            <el-button class="reset marginLeft10" type="primary" @click="reset()">重置</el-button>
            <el-button type="primary" @click="getArticleList" :loading="listLoading">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="main_table" style="min-height: 590px">
        <el-table ref="multipleTable" v-loading="listLoading" :data="list" element-loading-text="加载中" fit border
          highlight-current-row @selection-change="handleSelectionChange" :expand-row-keys="expands" :row-key='getRowKeys'
          @expand-change="expandChangeHandler">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.pic" border class="expand_table">
                <el-table-column type="index" label="序号" width="50">
                </el-table-column>
                <el-table-column label="广告简图" width="200">
                  <template slot-scope="scope">
                    <div class="logoStyle">
                      <div class="logo" v-for="(item, index) in scope.row.img">
                        <img :src="item.url" alt="">
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="跳转链接" prop="link" :show-overflow-tooltip="true" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="所属供应商" width="130" prop="school_id" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.school_id }}</template>
          </el-table-column>
          <el-table-column label="学校名称" width="130" prop="school_id" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.school_id }}</template>
          </el-table-column>

          <el-table-column label="广告位置" :show-overflow-tooltip="true">
            <template slot-scope="scope">

              <span>{{ scope.row.platform }} / {{ scope.row.pos }}</span>
            </template>
          </el-table-column>


          <el-table-column label="创建时间" prop="created_at" :show-overflow-tooltip="true" />
          <el-table-column label="广告状态" prop="status">
            <template slot-scope="scope">
              <el-switch :disabled="switchState" v-model="scope.row.status" active-color="#13ce66"
                inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="changeSwitch($event, scope.row)">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button @click="editAction(scope.row.id)" type="text" size="mini" class="handle_btn">修改</el-button>
              <el-button @click="deleteAction(scope.row.id)" type="text" size="mini" class="handle_btn">删除</el-button>
              <!-- <el-button @click="examine(scope.row.id)" type="text" size="mini" class="handle_btn">审核</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="main_page boxdq">
        <div></div>
        <div class="main_page_r">
          <el-pagination :current-page="current.page" :page-sizes="[20, 30, 50, 100]" :page-size="current.limit"
            layout="total, sizes, prev, pager, next, jumper" :total="totalCount" background @size-change="changeLimit"
            @current-change="changePage" />
        </div>
      </div>
    </div>


    <!-- 新增广告 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" destroy-on-close
      :close-on-click-modal="false" @close="closeCard">
      <el-row>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
          <el-col :span="24">
            <el-divider content-position="left">广告基本信息</el-divider>
          </el-col>
          <el-col :span="12">
            <!-- 使用searchSchool函数搜索学校,接口未出,先搭样子 -->
            <el-form-item label="学校名称" prop="school_id">
              <el-select style="width: 350px;" clearable v-model="ruleForm.school_id" filterable placeholder="请选择学校">
                <el-option v-for="item in schoolList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="广告平台/位置" prop="btn">
              <el-cascader style="width: 350px;" clearable v-model="ruleForm.btn" :options="options" :props="props"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="status">
              <el-select style="width: 350px;" clearable v-model="ruleForm.status" placeholder="请选择上架状态">
                <el-option label="上架" :value="1"></el-option>
                <el-option label="下架" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider content-position="left">广告详细信息</el-divider>
          </el-col>
          <el-col :span="24">
            <el-table class="expand_table" :data="tableData" border style="width: 100%">
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column width="120">
                <template slot="header" slot-scope="scope">
                  <span>排序</span>
                  <el-tooltip class="item" effect="dark" content="根据该属性进行轮播图的图片排序" placement="top-start">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-input v-model="scope.row.sort" placeholder="排序" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="广告图片">
                <template slot-scope="scope" style="height: 60px;">
                  <el-upload class="uploadSrc" :action="uploadPath" :data="{ store: 'document' }" list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="(response, file, fileList) => { handleRemove(response, file, fileList, scope.$index) }"
                    :multiple="false" :limit="1" :on-exceed="handleExceed"
                    :on-success="(response, file, fileList) => { handleSuccess(response, file, fileList, scope) }"
                    :file-list="scope.row.img">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible1" append-to-body>
                    <img class="openImg" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </template>
              </el-table-column>
              <el-table-column>
                <template slot="header" slot-scope="scope">
                  <span>广告跳转链接</span>
                </template>
                <template slot-scope="scope">
                  <el-input style="width: 350px;" v-model="scope.row.link" placeholder="广告跳转链接" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="addCard">新增</el-button>
                  <el-button type="text" size="small" v-if="tableData.length > 1"
                    @click="deleteCard(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCard">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadPath,
} from "@/api/currency";
import { Debounce } from '@/utils/index.js';
import {
  getDicionryInfo,
  // 查询广告列表
  queryOperate,
  // 新增/修改/删除广告
  addOperate,
  // 获取广告详情
  getOperateInfo,
} from "@/api/advertisement/index.js"
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  name: 'advertisement',
  data() {
    return {
      uploadPath,
      // 模态框标题
      dialogTitle: null,
      form: {
        // 学校名称
        school_id: null,
        // 广告状态
        status: null,
      },

      userType: [
        {
          name: '开启',
          id: 1
        }, {
          name: '关闭',
          id: 2
        }
      ],

      // 加载功能
      listLoading: false,
      // 列表字段
      list: [],

      // 分页
      current: {
        page: 1,
        limit: 20,
      },
      totalCount: 0,

      // 校验规则
      rules: {
        school_id: [
          { required: true, message: '请选择学校名称', trigger: 'change' }
        ],
        platform: [
          { required: true, message: '请选择广告平台', trigger: 'change' }
        ],
        pos: [
          { required: true, message: '请选择广告位置', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择上架状态', trigger: 'change' }
        ]
      },
      // 新增的模态框
      dialogVisible: false,
      // 新增的表单信息
      ruleForm: {
        // 名称
        school_id: null,
        btn: null,
        // 平台
        platform: null,
        // 位置
        pos: null,
        // 上架状态
        status: 1,
      },

      // 新增时的广告列表
      tableData: [],

      // 查看已上传的图片二级模态框
      dialogVisible1: false,
      // 查看已上传的图片链接
      dialogImageUrl: null,

      // 新增广告时,需选择对应的学校
      schoolList: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],


      // 广告平台/位置列表
      options: [],
      props: {
        value: 'val',
        label: 'name'
      },


      // 开关的禁用状态
      switchState: false,
      // 根据operateId判断是修改还是新增，存在operateId为修改，反之为新增
      operateId: null,

      // 配置每次表格的展开行只展示1行内容
      expands: [],
      getRowKeys(row) {
        return row.id;
      },
    }
  },
  created() {
    this.getArticleList()
  },
  methods: {
    // 获取广告平台/位置列表信息
    getPlatFormList() {
      return new Promise((resolve, reject) => {
        let data = {
          type: 'advertisment'
        }
        let param = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name, data)) +
              apiUrl().appsecret
            )
          },
          apiUrl().name,
          data
        );
        resolve(getDicionryInfo(param))
      })
    },
    // 获取学校列表信息
    searchSchool() {
      return new Promise((resolve, reject) => {
        resolve('1212')
      })
    },
    // 获取广告详情
    getOperate(id) {

      return new Promise((resolve, reject) => {
        let data = {
          id,
        }
        let param = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name, data)) +
              apiUrl().appsecret
            )
          },
          apiUrl().name,
          data
        );
        resolve(getOperateInfo(param))
      })
    },
    // 重置
    reset() {
      this.$refs['userListFrom'].resetFields();
    },
    // 搜索
    getArticleList() {
      this.listLoading = true
      let data = {
        school_id: this.form.school_id,
        status: this.form.status,
        page: this.current.page,
        per_page: this.current.limit
      }
      let param = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) +
            apiUrl().appsecret
          )
        },
        apiUrl().name,
        data
      );
      queryOperate(param).then(res => {
        if (res.errcode == 0) {
          this.list = res.data.list
          this.totalCount = res.data.count
          this.listLoading = false
        } else {
          this.$message.error(res.errmsg)
        }
      })
    },
    // 多选
    handleSelectionChange() {

    },

    // 新增
    editAction(id) {
      // 增加加载遮罩
      let _this = this
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      // 获取学校
      let searchSchoolApi = _this.searchSchool()
      // 获取广告平台/位置
      let platFormListApi = _this.getPlatFormList()
      // 根据id判断,存在id时为修改,反之则为新增
      if (id) {
        _this.operateId = id
        // 获取广告详情
        let getOperateApi = _this.getOperate(id)
        Promise.all([platFormListApi, searchSchoolApi, getOperateApi]).then((result) => {
          // 获取广告平台/位置列表
          let platFormList = result[0].data
          // 获取广告详情
          let operateList = result[2].data
          _this.options = platFormList
          _this.dialogTitle = '修改广告'
          // 赋值
          let { school_id, platform, pos, status, pic } = operateList
          this.ruleForm.school_id = school_id
          this.ruleForm.platform = platform
          this.ruleForm.pos = pos
          this.ruleForm.btn = [platform, pos]
          this.ruleForm.status = status
          this.tableData = pic
          loading.close();
          _this.dialogVisible = true
        })
      } else {
        let data = {
          sort: null,
          img: [],
          link: null,
        }
        _this.tableData.push(data)

        Promise.all([platFormListApi, searchSchoolApi]).then((result) => {
          // 获取广告平台/位置列表
          let platFormList = result[0].data
          _this.options = platFormList
          _this.dialogTitle = '新增广告'
          loading.close();
          _this.dialogVisible = true
        })
      }
    },
    // 新增广告位
    addCard() {
      let data = {
        sort: null,
        img: [],
        link: null,
      }
      this.tableData.push(data)
    },
    // 删除广告位
    deleteCard(row, index) {
      // console.log(row, index)
      console.log(this.tableData[index])
      this.$nextTick(() => {
        this.tableData.splice(index, 1)
      })
    },
    // 切换分页大小
    changeLimit(e) {
      this.current.limit = e
      this.getArticleList()
    },
    // 切换分页
    changePage(e) {
      this.current.page = e
      this.getArticleList()
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible1 = true
    },
    // 移除文件时的钩子
    handleRemove(response, file, fileList, index) {
      this.tableData[index].img = []
    },
    // 切换检索中的广告状态
    selectAction() {

    },
    // 上传图片时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 上传图片成功时的钩子
    handleSuccess(response, file, fileList, scope) {
      let dist = {
        name: file.name,
        url: response.data.src
      }
      this.$nextTick(() => {
        this.tableData[scope.$index].img.push(dist)
      }, 1000)
    },

    // 切换广告平台/位置
    handleChange(e) {
      this.ruleForm.platform = e[0]
      this.ruleForm.pos = e[1]
    },
    // 切换开关
    changeSwitch: Debounce(function (e, row) {
      this.switchState = true
      let data = {
        action: 'uptown',
        id: row.id,
        status: e
      }
      let param = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) +
            apiUrl().appsecret
          )
        },
        apiUrl().name,
        data
      );
      addOperate(param).then(res => {
        if (res.errcode == 0) {
          this.$message.success('修改成功')
          this.switchState = false
        } else {
          this.$message.error(res.errmsg)
        }
      })
    }),

    // 提交表单
    submit: Debounce(function () {
      let _this = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          /**
           * 1、判断基本信息完成
           * 2、 判断详细信息是否有数据，内容是否填写完成
           */
          try {
            _this.tableData.forEach((item, index) => {
              let values = Object.values(item)
              let deter = values.filter(list => {
                if (Array.isArray(list) && list.length != 0) {
                  return item
                }
                if (!list) {
                  return list
                }
              })
              if (deter.length == 0) {
                throw Error('请将信息补充完整!')
              }
            })
          } catch (e) {
            this.$message.error({
              message: e,
              type: 'error'
            });
            return false
          }

          // 获取广告列表并转成json传给后端
          let picJson = JSON.stringify(this.tableData)

          let data = {
            school_id: 1,
            pos: this.ruleForm.pos,
            platform: this.ruleForm.platform,
            status: this.ruleForm.status,
            pic: picJson
          }
          // 根据operateId判断是修改还是新增，存在operateId为修改，反之为新增
          if (this.operateId) {
            data.action = 'update'
            data.id = this.operateId
          } else {
            data.action = 'add'
          }
          let param = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, data)) +
                apiUrl().appsecret
              )
            },
            apiUrl().name,
            data
          );
          addOperate(param).then(res => {
            if (res.errcode == 0) {
              this.$message.success(res.errmsg || '操作成功')
              this.closeCard()
              this.getArticleList()
            } else {
              this.$message.error(res.errmsg || '操作失败')
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }),

    closeCard() {
      this.$refs.ruleForm.resetFields()
      this.tableData = []
      this.dialogVisible = false
    },

    // 点击展开的时候就会触发这个方法
    expandChangeHandler(row, expandedRows) {
      if (expandedRows.length) {
        this.expands = [];
        if (row) {
          this.expands.push(row.id);
        }
      } else {
        this.expands = [];
      }
    },

    getPicList() {

    },
    // 删除广告
    deleteAction(id) {
      let data = {
        action: 'del',
        id: id
      }
      let param = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) +
            apiUrl().appsecret
          )
        },
        apiUrl().name,
        data
      );
      this.$confirm('此操作将永久删除该广告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        addOperate(param).then(res => {
          if (res.errcode == 0) {
            this.$message.success('删除成功')
            this.getArticleList()
            loading.close();
          } else {
            this.$message.error(res.errmsg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.maincl {

  .more {
    margin-left: 50px;
  }

  .handle_btn {
    padding: 0;
    border: 0;
  }

  .edit_dialog {
    .address {
      max-width: 350px;
    }
  }

  .mainor_form form {
    width: 100%;
  }

  .logoStyle {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    overflow: auto;

    .logo {
      min-width: 100px;
      width: 100px;
      height: 67px;
      margin-right: 10px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .logoStyle::-webkit-scrollbar {
    width: 0;
    height: 0;
  }


  .main_table /deep/.el-table--small td {
    padding: 10px 0;
  }

  .main_table /deep/.el-table--small th {
    padding: 10px 0;
  }

  /deep/.el-table {
    tr {
      &:hover {
        background: none !important;
      }

      &.hover-row>td {
        background: none !important;
      }

      .current-row>td {
        background: none !important;
      }
    }
  }

  /deep/.main_table .el-table--small td .cell {
    height: auto !important;
  }

  /deep/.el-table .el-table__body tr:hover {
    background: #fff !important;
  }

  /deep/.el-table .el-table__body tr:hover>td {
    background: #fff !important;
  }

  /deep/.el-table tr.expanded+tr {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr>td {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr .mainex_ta {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr .mainex_ta th,
  /deep/.el-table tr.expanded+tr .mainex_ta tr {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr:hover {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr:hover>td {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr .el-table tr:hover {
    background: #fafafa !important;
  }

  /deep/.el-table tr.expanded+tr .el-table tr:hover>td {
    background: #fafafa !important;
  }

  /deep/.el-table .cell {
    display: flex;
    align-items: center;
  }

  /deep/.boxdq {
    justify-content: flex-end;
  }
}

/deep/.el-input {
  width: 100%;
}

.exptitle {
  padding: 10px 0px;
}

/deep/.uploadSrc .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
  left: 10px;
  top: 8px;

  i {
    font-size: 16px;
  }

}

/deep/.expand_table .el-table__row {
  height: 113px !important;
}

/deep/.uploadSrc {
  .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px
  }

  .el-upload-list--picture-card .el-upload-list__item:first-child {
    margin-left: 90px;
    margin-top: 0;
  }
}

.openImg {
  width: 300px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>